package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.entity.User;
import com.papercutting.platform.repository.UserRepository;
import com.papercutting.platform.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计数据控制器
 */
@RestController
@RequestMapping("/api/statistics")
@RequiredArgsConstructor
public class StatisticsController {
    
    private final CultureService cultureService;
    private final UserService userService;
    private final TutorialService tutorialService;
    private final NewsService newsService;
    private final UserRepository userRepository;
    
    /**
     * 获取平台总体统计信息
     */
    @GetMapping("/overview")
    public Result<Map<String, Object>> getOverviewStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取真实的统计数据
        stats.put("userCount", userService.getUserCount());
        stats.put("cultureCount", cultureService.findAll().size());
        stats.put("tutorialCount", tutorialService.findAll().size());
        stats.put("newsCount", newsService.findAll().size());
        
        // 学习记录统计（暂时设为0，如果有UserStudyService可以添加）
        stats.put("studyCount", 0);
        
        return Result.success(stats);
    }
    
    /**
     * 获取用户相关统计信息
     */
    @GetMapping("/user")
    public Result<Map<String, Object>> getUserStats() {
        return Result.success(userService.getUserStats());
    }
    
    /**
     * 获取内容相关统计信息
     */
    @GetMapping("/content")
    public Result<Map<String, Object>> getContentStats() {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("cultureCount", cultureService.findAll().size());
        stats.put("tutorialCount", tutorialService.findAll().size());
        stats.put("newsCount", newsService.findAll().size());
        
        return Result.success(stats);
    }
    
    /**
     * 获取学习相关统计信息
     */
    @GetMapping("/study")
    public Result<Map<String, Object>> getStudyStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 学习记录统计暂时返回固定值
        stats.put("studyRecordCount", 0);
        stats.put("completedUsers", 0);
        stats.put("averageProgress", 0.0);
        
        return Result.success(stats);
    }
    
    /**
     * 获取用户增长趋势
     * @param period 时间周期：week（周）、month（月）、year（年）
     */
    @GetMapping("/user-growth")
    public Result<Map<String, Object>> getUserGrowthTrend(@RequestParam(defaultValue = "week") String period) {
        Map<String, Object> result = new HashMap<>();
        List<String> labels = new ArrayList<>();
        List<Integer> data = new ArrayList<>();
        
        LocalDateTime now = LocalDateTime.now();
        List<User> allUsers = userRepository.selectList(null);
        
        if ("week".equals(period)) {
            // 本周数据（按天统计）
            for (int i = 6; i >= 0; i--) {
                LocalDateTime startOfDay = now.minusDays(i).toLocalDate().atStartOfDay();
                LocalDateTime endOfDay = startOfDay.plusDays(1);
                
                long count = allUsers.stream()
                    .filter(u -> u.getCreateTime() != null)
                    .filter(u -> !u.getCreateTime().isBefore(startOfDay) && u.getCreateTime().isBefore(endOfDay))
                    .count();
                
                labels.add(getDayLabel(i));
                data.add((int) count);
            }
        } else if ("month".equals(period)) {
            // 本月数据（按周统计）
            for (int i = 3; i >= 0; i--) {
                LocalDateTime startOfWeek = now.minusWeeks(i);
                LocalDateTime endOfWeek = now.minusWeeks(i - 1);
                
                long count = allUsers.stream()
                    .filter(u -> u.getCreateTime() != null)
                    .filter(u -> !u.getCreateTime().isBefore(startOfWeek) && u.getCreateTime().isBefore(endOfWeek))
                    .count();
                
                labels.add("第" + (4 - i) + "周");
                data.add((int) count);
            }
        } else if ("year".equals(period)) {
            // 本年数据（按月统计）
            for (int i = 1; i <= 12; i++) {
                LocalDateTime startOfMonth = LocalDate.of(now.getYear(), i, 1).atStartOfDay();
                LocalDateTime endOfMonth = i < 12 ? 
                    LocalDate.of(now.getYear(), i + 1, 1).atStartOfDay() : 
                    LocalDate.of(now.getYear() + 1, 1, 1).atStartOfDay();
                
                long count = allUsers.stream()
                    .filter(u -> u.getCreateTime() != null)
                    .filter(u -> !u.getCreateTime().isBefore(startOfMonth) && u.getCreateTime().isBefore(endOfMonth))
                    .count();
                
                labels.add(i + "月");
                data.add((int) count);
            }
        }
        
        result.put("labels", labels);
        result.put("data", data);
        result.put("period", period);
        
        return Result.success(result);
    }
    
    /**
     * 获取星期几的标签
     */
    private String getDayLabel(int daysAgo) {
        LocalDate date = LocalDate.now().minusDays(daysAgo);
        int dayOfWeek = date.getDayOfWeek().getValue();
        
        switch (dayOfWeek) {
            case 1: return "周一";
            case 2: return "周二";
            case 3: return "周三";
            case 4: return "周四";
            case 5: return "周五";
            case 6: return "周六";
            case 7: return "周日";
            default: return "";
        }
    }
}
